package com.fh.common.system.api.impl;

import com.fh.common.components.redis.RedisActor;
import com.fh.common.constant.ActionLogResult;
import com.fh.common.system.api.ISysBaseAPI;
import com.fh.common.util.DateUtils;
import com.fh.common.util.IPUtils;
import com.fh.common.util.SpringContextUtils;
import com.fh.modules.shiro.ShiroUtils;
import com.fh.modules.system.entity.SysLog;
import com.fh.modules.system.entity.SysUser;
import com.fh.modules.system.mapper.SysLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 
 * @author junqiu
 *
 */
@Service
public class SysBaseAPI implements ISysBaseAPI {
//	@Value("${log.indb.type:mysql}")
//	private String logIndbType;
	@Resource
	private SysLogMapper sysLogMapper;
//	@Autowired
//	private SysLogMongoService sysLogMongoService;
	@Autowired
	private RedisActor redisActor;
	@Override
	public void addLog(String userId, String logContent, Integer logType, Integer operatetype,ActionLogResult actResult,String resultMessage) {
		SysLog sysLog=this.initSysLog(userId, logContent, logType, operatetype,actResult,resultMessage);
//		if(Constant.LOG_DB_MONGODB.equals(logIndbType)) {
//			//保存系统日志
//			sysLogMongoService.saveLog(sysLog);
//		}
		sysLogMapper.insert(sysLog);
	}
	
	@Override
	public void addLog(String logContent, Integer logType, Integer operatetype,ActionLogResult actResult,String resultMessage) {
		SysLog sysLog=this.initSysLog("", logContent, logType, operatetype,actResult,resultMessage);
//		if(Constant.LOG_DB_MONGODB.equals(logIndbType)) {
//			//保存系统日志
//			sysLogMongoService.saveLog(sysLog);
//		}
		sysLogMapper.insert(sysLog);
	}
	
	public SysLog initSysLog(String userId,String logContent, Integer logType, Integer operatetype,ActionLogResult actResult,String resultMessage) {
		SysLog sysLog = new SysLog();
		//注解上的描述,操作日志内容
		sysLog.setLogContent(logContent);
		sysLog.setLogType(logType);
		sysLog.setOperateType(operatetype);
		sysLog.setActResultMessage(resultMessage);
		sysLog.setActResult(actResult.getValue());
		//获取request
		HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));

		//获取登录用户信息
		SysUser sysUser = (SysUser) ShiroUtils.getShiroPrincipal();
		if(sysUser!=null){
			sysLog.setUserid(sysUser.getUsername());
			sysLog.setUsername(sysUser.getRealname());

		}else {
			sysLog.setUserid(userId);
		}
		sysLog.setCreateTime(new Date());
		
		return sysLog;
	}

	@Override
	public void addPV() {
		String today=DateUtils.formatDate();
		redisActor.incr("PV-"+today, 1);
		redisActor.incr("PV-history", 1);
		
	}

	@Override
	public void addUV() {
		
	}

	

}
